//
//  QSMenuControllerLabel.swift
//  KetogenicNutritionist
//
//  Created by Song on 2019/6/15.
//  Copyright © 2019 Song. All rights reserved.
//

import UIKit

class QSMenuControllerLabel: UILabel {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setupLabelLongPressGes()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 必须重写这个方法
    override var canBecomeFirstResponder: Bool {
        get {
            return true
        }
    }
    
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        let actionName = NSStringFromSelector(action)
        if actionName.hasPrefix("normalAction") {
            return true
        }
        
        return false
    }
    
    // MARK: - Func
    /// 单击
    private func setupLabelTapGes() {
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(tapGest))

        self.addGestureRecognizer(tap)
    }
    
    /// 创建长按手势
    private func setupLabelLongPressGes() {
        let longPressGes = UILongPressGestureRecognizer(target: self, action: #selector(labelLongPressAction))
        // 长按手势最小触发时间
        longPressGes.minimumPressDuration = 1
        
        self.addGestureRecognizer(longPressGes)
    }
    
    /// 长按方法
    @objc private func labelLongPressAction(){
        // 如果 Menu 已经被创建那就不再重复创建 menu
        if (UIMenuController.shared.isMenuVisible){
            return
        }
        
        // 要成为第一响应者否则某些功能会错乱
        self.becomeFirstResponder()
        
        let menuCtl = UIMenuController.shared
        
        // 设置 Menu 所显示的 items和对应调用的方法
        var menuItemArr = [UIMenuItem]()
        
        for i in 0 ..< menuArray.count {
            let menuModel = menuArray[i]
            if let til = menuModel.title {
                let actionStr = "normalAction" + "\(i)"
                let menu = UIMenuItem.init(title: til, action: Selector.init(actionStr))
                menuItemArr.append(menu)
            }
        }
        menuCtl.menuItems = menuItemArr
        
        // 设置箭头方向
        menuCtl.arrowDirection = .default
        
        var width: CGFloat = 0.0
        let textWidth = (self.text ?? "").qs_obtainWidth(font: self.font, height: 30)
        if textWidth < self.qs_width {
            width = textWidth
        } else {
            width = self.qs_width
        }
        
        // 设置添加上 menu 的目标控件的 rect 和目标控件
        menuCtl.setTargetRect(CGRect.init(x: 0.0, y: 0.0, width: width + leftIndent, height: self.qs_height), in: self)
        // 令 Menu 可见
        menuCtl.setMenuVisible(true, animated: true)
    }
    
    /// 单击方法
    @objc private func tapGest() {
        if self.tapAction != nil {
            self.tapAction!()
        }
    }
    
    /// 通用点击item的方法
    @objc private func normalAction0() {
        self.executeAction(index: 0)
    }
    
    @objc private func normalAction1() {
        self.executeAction(index: 1)
    }
    
    @objc private func normalAction2() {
        self.executeAction(index: 2)
    }
    
    @objc private func normalAction3() {
        self.executeAction(index: 3)
    }
    
    @objc private func normalAction4() {
        self.executeAction(index: 4)
    }
    
    /// 执行哪个操作
    private func executeAction(index: Int) {
        let item = menuArray[index]
        if let block = item.action {
            block()
        }
    }
    
    // MARK: - Property
    // 点击触发
    var tapAction: (() -> ())? {
        didSet {
            if tapAction != nil {
                self.setupLabelTapGes()
            }
        }
    }
    // 要做的操作数组
    var menuArray = Array<QSMenuControllerModel>() {
        didSet {
            assert(menuArray.count <= 5, "目前最多只能自定义5个按钮")
        }
    }
    // 左边缩进
    var leftIndent: CGFloat = 0.0
}
